package com.hengyue.common.core.baseenum;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import jakarta.persistence.AttributeConverter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@SuppressWarnings("all")
public interface IBaseEnum<R extends IBaseEnum<R>> {

    default void initEnum(Integer code, String description) {
        EnumContainer.putEnum(this, code, description);
    }

    @JsonValue
    default Integer getCode() {
        return EnumContainer.getEnum(this).code();
    }

    default String getDescription() {
        return EnumContainer.getEnum(this).description();
    }

    @JsonCreator
    R getByCode(Integer code);

    default R getByCode(Class<R> clazz, Integer code) {
        for (R enumConstant : clazz.getEnumConstants()) {
            if (enumConstant.getCode().equals(code)) {
                return enumConstant;
            }
        }
        return null;
    }

    static Integer cover2Integer() {
        return null;
    }

    class EnumContainer {
        private static final Map<IBaseEnum, EnumBean> ENUM_MAP = new ConcurrentHashMap<>();

        public static void putEnum(IBaseEnum baseEnum, Integer code, String description) {
            ENUM_MAP.put(baseEnum, new EnumBean(code, description));
        }

        static <K extends IBaseEnum, Integer> EnumBean getEnum(K dict) {
            return ENUM_MAP.get(dict);
        }
    }

    record EnumBean(Integer code, String description) {
    }
}
